package com.zim.aliot.service.impl;

import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.zim.aliot.constant.RedisConstant;
import com.zim.aliot.dataobject.CarsDo;
import com.zim.aliot.entity.IOTStatus;
import com.zim.aliot.service.CarsService;
import com.zim.aliot.service.StatusService;
import com.zim.aliot.vo.VehicleVO;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class StatusServiceImpl implements StatusService{
	
    @Autowired
    private CarsService carsService;
    
    @Resource
    private RedisTemplate<String, VehicleVO> redisTemplate;
    
    
    /**
     * 设备状态处理
     * @param iotStatus
     */
    public void deviceInfo(IOTStatus iotStatus) {
    	CarsDo carsDo = null;
    	String vin = "";
    	try {
    		carsDo = carsService.find(iotStatus.getDeviceName());
		} catch (Exception e) {
			log.error("[ 设备号不存在(设备状态处理) ]:{}",e.getMessage());
		}
    	if(null == carsDo) {
    		return;
    	}else {
    		vin = carsDo.getVin();
    	}
    	VehicleVO vehicleVO = redisTemplate.opsForValue().get(vin);
    	
    	if(("offline").equals(iotStatus.getStatus())) {
    		deviceOffline(vin, vehicleVO);
    	}else if (("online").equals(iotStatus.getStatus())) {
			deviceOnline(vin, vehicleVO);
		}
    	
    }
    
    protected void deviceOnline(String vin,VehicleVO vehicleVO) {
    	log.info("在线取出正常数据:{}",vehicleVO);
        if(null == vehicleVO) {
        	VehicleVO vo = new VehicleVO();
        	vo.setNetwork_status(1);
        	redisTemplate.opsForValue().set(vin, vo, RedisConstant.EXPIRE,TimeUnit.SECONDS);
        }else {
        	vehicleVO.setNetwork_status(1);
        	redisTemplate.opsForValue().set(vin, vehicleVO, RedisConstant.EXPIRE, TimeUnit.SECONDS);
        }
    }
    
    protected void deviceOffline(String vin,VehicleVO vehicleVO) {
    	log.info("离线取出正常数据:{}",vehicleVO);
    	if(null == vehicleVO) {
        	VehicleVO vo = new VehicleVO();
        	vo.setNetwork_status(0);
        	redisTemplate.opsForValue().set(vin, vo, RedisConstant.EXPIRE,TimeUnit.SECONDS);
        }else {
        	vehicleVO.setNetwork_status(0);
        	redisTemplate.opsForValue().set(vin, vehicleVO, RedisConstant.EXPIRE, TimeUnit.SECONDS);
        }
    }
}
